/*
 * Created by: Peter Weissbrod
 * Created: Tuesday, November 27, 2007
 */
using System;
using System.Web;
using Castle.ActiveRecord;

namespace ASP.App_Code
{
    /// <summary>
    /// implementing the session-per-request model as displayed inside of
    /// http://using.castleproject.org/display/AR/Enable+Session+per+Request
    /// </summary>
    public class GlobalApplication : HttpApplication
    {
        public GlobalApplication()
        {
            BeginRequest += new EventHandler(GlobalApplication_BeginRequest);
            EndRequest += new EventHandler(GlobalApplication_EndRequest);
        }
        /// <summary>
        /// A session object is a very lightweight construct used for database interaction
        /// we build and destroy these along with the lifetime of a page request
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GlobalApplication_EndRequest(object sender, EventArgs e)
        {
            try
            {
                SessionScope scope = HttpContext.Current.Items["nh.sessionscope"] as SessionScope;
                if (scope != null)
                {
                    scope.Dispose();
                }
            }
            catch (Exception ex)
            {
                HttpContext.Current.Trace.Warn("Error", "EndRequest: " + ex.Message, ex);
            }
        }
        /// <summary>
        /// initiate the session
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GlobalApplication_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Items.Add("nh.sessionscope", new SessionScope());
        }
    }
}